export default function useContextMenu(container) {
  const x = ref(0)
  const y = ref(0)
  const visible = ref(false)

  onMounted(async () => {
    await nextTick()
    const el = _getChildren()
    el?.addEventListener('contextmenu', openMenu)
    window.addEventListener('click', closeMenu)
    window.addEventListener('contextmenu', closeMenu)
  })
  onUnmounted(() => {
    const el = _getChildren()
    el?.removeEventListener('contextmenu', openMenu)
    window.removeEventListener('click', closeMenu)
    window.removeEventListener('contextmenu', closeMenu)
  })

  function openMenu(e) {
    console.log(_isInElement(e))
    e.preventDefault()
    e.stopPropagation()
    x.value = e.clientX
    y.value = e.clientY
    visible.value = _isInElement(e)
    // visible.value = true
  }

  function closeMenu() {
    visible.value = false
  }

  // 右键位置是否在元素内
  function _isInElement(event) {
    const el = _getChildren()
    const rect = el?.getBoundingClientRect()
    const x = event.clientX
    const y = event.clientY

    return (
      x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom
    )
  }

  function _getChildren() {
    const el = container.value
    if (!el || !el.children) return null
    return el?.children[0]
  }

  return {
    x,
    y,
    visible,
  }
}
